<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:setBundle basename="messages.realtime"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">

<title>Localizador GPS</title>
<style type="text/css">
    v\:* {
      behavior:url(#default#VML);
    }
</style>

<script type="text/javascript">
//<![CDATA[


var map;
var url="/VEGPS/ServletGoogleGPS?p=getPos";
var http = getHTTPObject();
var gMarker;
var points;
var gPolyline;
var time=new Date();
var ruta;
var datos;
var i=0;

var timer;
var stopRefresh=false;

function parseDate(str) {
  var ts=str.split(" ");
  var d=ts[0].split("-");
  var h=ts[1].split(":");
  var s=h[2].split(".");

  var fecha=new Date(Date.UTC(d[0], d[1] - 1, d[2], h[0], h[1], s[0], s[1]));

  return(fecha);
}

function load() {
   if(map == undefined) {
     var script;

     var head = document.getElementsByTagName("head")[0];
     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'mapLib';
     head.appendChild(script);
     script.src = "http://www.google.com/jsapi?key=ABQIAAAANdXnaDQ5-BE42sETh1OnBxQSUI96VjuXJJ7uIyuEjKZOYLINbRQ00Oj1snry5mEp_2LhV3da9mA0JQ&callback=load2";
   } else {
     showMap();
   }
}

function showMap() {
     var mapType=map.getCurrentMapType();
     if(mapType!=G_NORMAL_MAP && mapType!=G_SATELLITE_MAP && mapType!=G_HYBRID_MAP)
        map.setMapType(G_HYBRID_MAP);
     var point=new GLatLng(parent.latitudAnterior, parent.longitudAnterior);
     map.removeOverlay(gMarker);
     gMarker=new GMarker(point, null);
     map.addOverlay(gMarker);
     map.setZoom(parent.zoomLevel);
     point=new GLatLng(parent.latitud, parent.longitud);
     map.panTo(point);
     if(points.length + parent.nPoints > 1000)
	points=points.slice(points.length+parent.nPoints-1000);
     for(i=points.length;i<parent.latitudes.length;i++) {
       point=new GLatLng(parent.latitudes[i], parent.longitudes[i]);
       points.push(point);
     }
     parent.nPoints=0;
     mapMostrarRuta();
     stopRefresh=false;
     timer=window.setTimeout("actualizarMapa();", 0);
}

function load2() {
     google.load("maps", "2", {"callback" : init});
}

function init() {
     var script;
     var head = document.getElementsByTagName("head")[0];
     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'pano1';
     head.appendChild(script);
     script.src = "../scripts/markermanager.js";

     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'pano2';
     head.appendChild(script);
     script.src = "../scripts/pano_layer.js";

     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'pano3';
     head.appendChild(script);
     script.src = "../scripts/pano_maptypecontrol.js";

     loadMaps();
}

function loadMaps() {
    if(typeof(PanoMapTypeControl)=="undefined") {
        window.setTimeout("loadMaps();", 100);
        return;
    }

    if(GBrowserIsCompatible()) {
	gMarker = new GMarker(0, 0);

	points=[];

	map = new GMap2(document.getElementById("map"));
	map.addMapType(G_SATELLITE_3D_MAP);
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(0, 0), 14);
	map.addControl(new PanoMapTypeControl());
        map.enableScrollWheelZoom();
        map.enableContinuousZoom();
	map.setMapType(G_HYBRID_MAP);

	showMap();
    }
}

function switchMap() {
  clearTimeout(timer);
  stopRefresh=true;
  parent.zoomLevel=map.getZoom();
  var centerPos=map.getCenter();
  parent.latitud=centerPos.lat();
  parent.longitud=centerPos.lng();
  parent.document.getElementById("VE").style.display="block";
  parent.document.getElementById("GM").style.display="none";
  parent.WIN=parent.frames['VE'];

  parent.VE.load();
}

function getHTTPObject() {
	var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
                 } catch (e) {}
            }
        }

        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        } else {
	    return http_request;
	}
}



function handleHttpResponse() {

    if (http.readyState == 4) {
        if (http.status == 200) {
    try {

      results=http.responseText.split(";");

      var grados;
      var latitudNMEA=results[1];
      var longitudNMEA=results[2];


      grados=Math.floor(latitudNMEA/1000000);
      if(grados<0)
	grados=grados+1;
      var latitud=(latitudNMEA/1000000-grados)/0.6+grados;
      grados=Math.floor(longitudNMEA/1000000);
      if(grados<0)
	grados=grados+1;
      var longitud=(longitudNMEA/1000000-grados)/0.6+grados;

      if(!parent.primerDato) {
          var dx=6370*(latitud-parent.latitudAnterior)*Math.PI/180;
          var dy=6370*Math.cos(latitud*Math.PI/180)*(longitud-parent.longitudAnterior)*Math.PI/180;
          parent.distancia+=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2));
      } else {
          parent.primerDato=false;
      }
      parent.latitudAnterior=latitud;
      parent.longitudAnterior=longitud;

      var fecha=parseDate(results[0]);
      var velocidad=Math.round(results[3] / 10);
      var altitud=results[5];

      if(fecha.getTime() != time.getTime()) {
        var point = new GLatLng(latitud, longitud);
        if(points.length>=1000) {
	  points.shift();
	  parent.latitudes.shift();
	  parent.longitudes.shift();
        }
        points.push(point);
        parent.latitudes.push(latitud);
        parent.longitudes.push(longitud);
        parent.nPoints+=1;

        if(parent.mostrarRuta) {
	  if(gPolyline!=undefined)
	    map.removeOverlay(gPolyline);
	  gPolyline=new GPolyline(points);
	  map.addOverlay(gPolyline);
        }

        map.removeOverlay(gMarker);
        gMarker=new GMarker(point, null);
        map.addOverlay(gMarker);

        map.panTo(new GLatLng(latitud, longitud));
        time = fecha;
      }

      parent.document.getElementById("fecha").innerHTML=fecha.toLocaleDateString();
      parent.document.getElementById("hora").innerHTML=fecha.toLocaleTimeString();
      parent.document.getElementById("velocidad").innerHTML=velocidad + " km/h";
      parent.document.getElementById("distancia").innerHTML=Math.round(parent.distancia*1000)/1000 + " km";
      parent.document.getElementById("altitud").innerHTML=altitud + " m";
    } catch (err) {}

    if(!stopRefresh)
      timer=window.setTimeout("actualizarMapa();", 1000);

        } else {
//            alert('There was a problem with the request.');
        }
    }
}

function actualizarMapa() {

        http.open('GET', url, true);
        http.onreadystatechange = handleHttpResponse;
        http.send(null);

}

function fMostrarRuta(boton) {
    if(parent.mostrarRuta) {
      boton.value="<fmt:message key="button.route.1"/>";
      boton.title="<fmt:message key="button.route.title.1"/>";
      parent.mostrarRuta=false;
    } else {
      boton.value="<fmt:message key="button.route.2"/>";
      boton.title="<fmt:message key="button.route.title.2"/>";
      parent.mostrarRuta=true;
    }
    mapMostrarRuta();
}

function mapMostrarRuta() {
    if(gPolyline!=undefined) {
      map.removeOverlay(gPolyline);
      gPolyline=undefined;
    }
    if(parent.mostrarRuta) {
      gPolyline=new GPolyline(points);
      map.addOverlay(gPolyline);
    }
}

function fReset() {
    parent.distancia=0;
    parent.document.getElementById("distancia").innerHTML="0 km";
}

function unload() {
    GUnload();
}

//]]>
</script>

</head>

<body onunload="unload()">
  <div id="map" style="width: 500px; height: 300px"></div>
</body>

</html>


